//
//  CalculatorBrain.swift
//  SwiftUI-Calculator
//
//  Created by gree on 2020/9/27.
//

import SwiftUI

enum CalculatorBrain {
    case left(String)
    case leftOp(
            left: String,
            op: CalculatorButtonItem.Op
         )
    case leftOpRight(
            left: String,
            op: CalculatorButtonItem.Op,
            right: String
         )
    case error
}

extension CalculatorBrain {
    /// 操作的时候，显示的是什么字符串
    var output: String {
        var result: String
        switch self {
            case .left(let left):
                result = left
            case .leftOp(let left, _):
                result = left
            case .leftOpRight( _, _, let right):
                result = right
            case .error:
                result = ""
        }
        guard let value = Double(result) else {
            return "ERROR"
        }
        return formatter.string(from: value as NSNumber)!
    }
    
    var formatter: NumberFormatter {
        let f = NumberFormatter()
        f.minimumFractionDigits = 0
        f.maximumFractionDigits = 8
        f.numberStyle = .decimal
        return f
    }
    
//    func apply(item: CalculatorButtonItem) -> CalculatorBrain {
//        switch item {
//        case .digit(let num):
//            return apply(item: .digit(num))
//        case .dot:
//            return ap
//        case .op(let op):
//            return apply(op: op)
//        case .command(let command):
//            return apply(command: command)
//        }
//    }
}
